package com.lemon.smartsafetynew.util.crash;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafetynew.util.common.CommonUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * Created by Andrew on 2017/10/18.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";

    private static final CrashHandler ourInstance = new CrashHandler();

    private Context context;

    public static CrashHandler getInstance() {
        return ourInstance;
    }

    private CrashHandler() {
        context = IApplication.context();

    }

    public void init() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        try {

            PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(FileUtil.getAppLogTempDir(context)
                    + File.separator + CommonUtil.timeToStr4(new Date()))), true);
            pw.println(obtainExceptionInfo(throwable));
            pw.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        System.exit(1);
    }

    /**
     * Catch Exception Error
     *
     * @param throwable
     * @return
     */
    private String obtainExceptionInfo(Throwable throwable) {
        StringWriter mStringWriter = new StringWriter();
        PrintWriter mPrintWriter = new PrintWriter(mStringWriter);
        throwable.printStackTrace(mPrintWriter);
        mPrintWriter.close();

        Log.e(TAG, mStringWriter.toString());
        return mStringWriter.toString();
    }

}
